<template>
  <div>
    <Header :title="`${addressId? '编辑地址':'新增地址'}`"></Header>
    <div class="card">
      <form>
        <div class="row">
          <text class="header">收货人</text>
          <div class="greyCard">
            <input
                v-model="addressDetail.name"
                placeholder="名字"
                class="input"
            />
          </div>
        </div>
        <div style="height: 10px"></div>
        <div class="row">
          <text class="header">手机号</text>
          <div class="greyCard">
            <input
                v-model="addressDetail.telephone"
                placeholder="手机号"
                class="input"
            />
          </div>
        </div>
        <div style="height: 10px"></div>

        <div class="row">
          <text class="header">所在地区</text>
          <div class="greyCard">
            <div
                class="row"
                @click="show = true"
                style="justify-content: space-between"
            >
              <div style="color: grey">
                {{
                  ((addressDetail.provinceName || '') +
                      (addressDetail.cityName || '') +
                      (addressDetail.areaName || '') +
                      (addressDetail.streetName ||
                          '')) ||
                  '省、市、区、街道'
                }}
              </div>
              <text style="color: grey">＞</text>
            </div>
            <van-popup v-model:show="show" round position="bottom">
              <van-cascader
                  v-model="cascaderValue"
                  title="请选择所在地区"
                  :options="options"
                  @close="show = false"
                  @finish="onFinish"
                  @change="onChange"
              />
            </van-popup>
          </div>
        </div>
        <div style="height: 10px"></div>

        <div class="row">
          <text class="header">详细地址</text>
          <div class="greyCard">
            <input
                v-model="addressDetail.address"
                placeholder="详细地址"
                class="input"
            />
          </div>
        </div>
        <div style="height: 10px"></div>

        <div class="row" style="justify-content: space-between">
          <text class="header" style="width: 200px">设为默认地址</text>
          <van-switch v-model="isDefault" @change="handleSwitch"/>

          <!-- <switch
            :checked="addressDetail.isDefault === 1"
            @change="handleSwitch"
          ></switch> -->
        </div>
      </form>
    </div>
    <div class="bottom">
      <van-button
          round
          type="primary"
          @click="submit"
          size="large"
          :loading="loading"
      >保存
      </van-button
      >
    </div>
    <div style="display: flex; justify-content: center; align-items: center">
      <van-loading
          class="loading-bg"
          type="spinner"
          color="#303030"
          size="24px"
          v-show="pageLoading"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
// import { onLoad, onPullDownRefresh } from '@dcloudio/uni-app'
import {ref} from 'vue'
// import request from '@/utils/request'
import {showToast} from 'vant'
import {useRoute} from 'vue-router' //1.先在需要跳转的页面引入useRouter
const {query, params} = useRoute() //2.在跳转页面定义router变量，解构得到指定的query和params传参的参数
import adminRequest from '@/utils/adminRequest'
import api from '@/api/index.js'
import router from "@/router";

const pageLoading = ref(false)
console.log('query params', query, params)
// const { windowWidth } = uni.getSystemInfoSync()
const addressDetail = ref({})
const isDefault = ref(false)
const addressId = query.id
const loading = ref(false)
const show = ref(false)

function showPicker() {
  show.value = true
}

const options = ref([
  // {
  //   text: '浙江省',
  //   value: '330000',
  //   children: [],
  // },
  // {
  //   text: '江苏省',
  //   value: '320000',
  //   children: [{ text: '南京市', value: '320100' }],
  // },
])
api.getDistrictApi({level: 1}).then((res) => {
  console.log(res)
  if (res.code === '200') {
    options.value = res.data.map((e) => {
      return {
        text: e.label,
        value: e.code,
        children: [],
        id: e.id,
      }
    })
  }
})

function onFinish({selectedOptions}) {
  // show.value = false
  // console.log('onFinish selectedOptions', selectedOptions.selectedOptions)
}

const onChange = ({value, tabIndex, selectedOptions}) => {
  // console.log(
  //     'onChange value,tabIndex selectedOptions',
  //     value,
  //     tabIndex,
  //     selectedOptions
  // )
  // console.log('options',options.value)
  const optionsCurrent = selectedOptions[selectedOptions.length - 1]
  if (tabIndex === 0) {
    addressDetail.value.provinceName = optionsCurrent.text
    addressDetail.value.provinceCode = optionsCurrent.value

    addressDetail.value.cityName = null
    addressDetail.value.cityCode = null

    addressDetail.value.areaName = null
    addressDetail.value.areaCode = null

    addressDetail.value.streetName = null
    addressDetail.value.streetCode = null


  } else if (tabIndex === 1) {
    addressDetail.value.cityName = optionsCurrent.text
    addressDetail.value.cityCode = optionsCurrent.value

    addressDetail.value.areaName = null
    addressDetail.value.areaCode = null

    addressDetail.value.streetName = null
    addressDetail.value.streetCode = null
  } else if (tabIndex === 2) {
    addressDetail.value.areaName = optionsCurrent.text
    addressDetail.value.areaCode = optionsCurrent.value

    addressDetail.value.streetName = ''
    addressDetail.value.streetCode = ''

  } else if (tabIndex === 3) {
    addressDetail.value.streetName = optionsCurrent.text
    addressDetail.value.streetCode = optionsCurrent.value
  }
  // console.log('optionsCurrentdddddddddd', optionsCurrent)
  // console.log('optionsCurrent.children 111', optionsCurrent.children)

  if (!optionsCurrent.children?.length) {
    api
        .getDistrictApi({
          pid: optionsCurrent.id,
        })
        .then((res) => {
              if (res?.data?.length) {
                optionsCurrent.children = res.data.map((e) => {
                  return {
                    text: e.label,
                    value: e.code,
                    children: null,
                    id: e.id,
                  }
                })
                // console.log('optionsCurrent.children res', optionsCurrent.children)
              } else {
                // console.log('el;se')
                show.value = false


              }
            }
        )
  }
}
const cascaderValue = ref({})
if (addressId) {
  pageLoading.value = true
  api
      .getAddressDetail(addressId)
      .then((res) => {
        if (res.code === '200') {
          addressDetail.value = res.data
          isDefault.value = addressDetail.value.isDefault === 1
        }
      })
      .finally(() => {
        pageLoading.value = false
      })
}

function handleSwitch(e) {
  addressDetail.value.isDefault = isDefault.value ? 1 : 0
  console.log(addressDetail.value)
}

async function submit() {
  loading.value = true
  addressDetail.value.postalCode = `${addressDetail.value.provinceName||''}${addressDetail.value.cityName||''}${addressDetail.value.areaName||''}${addressDetail.value.streetName||''}`
  setTimeout(() => {
    var future
    //更新
    if (!addressId) {
      future = adminRequest({
        url: '/wl-portal/portal/address/save',
        method: 'post',
        data: addressDetail.value,
      })
    } else {
      future = adminRequest({
        url: '/wl-portal/portal/address/update',
        method: 'put',
        data: addressDetail.value,
      })
    }
    future
        .then((res) => {

          if (res.code == '200') {

            showToast('保存成功')
            router.back()
          }

        })
        .finally(() => {
          loading.value = false
        })
  }, 1)
}
</script>

<style scoped lang="scss">
.input {
  border: none;
  background-color: transparent;
}

.bottom {
  position: fixed;
  bottom: calc(var(--window-bottom));
  z-index: 1030;
  margin-bottom: 20px;
  justify-content: center;
  width: 100%;
  padding: 16px;
  box-sizing: border-box;
}

.submit {
  background-color: #ec6a2c;
  border-radius: 999px;
  width: 100%;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-size: 16px;
  font-weight: 500;
  line-height: 22px;
  letter-spacing: 0px;
  text-align: center;
}

.row {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.card {
  border-radius: 16px;
  background-color: white;
  padding: 20px;
  box-sizing: border-box;
}

.header {
  font-family: PingFang SC;
  font-size: 13px;
  font-weight: 400;
  line-height: 22px;
  letter-spacing: 0px;
  text-align: left;
  color: black;
  width: 74px;
}

.placeHolder {
  font-family: PingFang SC;
  font-size: 14px;
  font-weight: 400;
  line-height: 22px;
  letter-spacing: 0px;
  text-align: center;
}

.greyCard {
  width: 100%;
  padding: 10px;
  border-radius: 8px;
  background-color: #fafafa;
  flex-grow: 1;
}
</style>
